package net.inxweb.bluemeerkat.infra.jcr.jackrabbit;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;

import javax.jcr.Binary;
import javax.jcr.LoginException;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;

import org.apache.jackrabbit.core.TransientRepository;
import org.apache.jackrabbit.value.BinaryImpl;

public class Test {
	private static final String USERNAME = "username";
	private static final char[] PASSWORD = "password".toCharArray();

	/**
	 * @param args
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public static void main(String[] args) throws FileNotFoundException, IOException {
		Repository repository = new TransientRepository();

		Session session = null;

		try {
			session = repository.login(new SimpleCredentials(USERNAME, PASSWORD)); 
		 

			Node root = session.getRootNode();

			Node folderNode = root.addNode("eded3", "nt:folder");  
			
			
			File file = new File("c:/", "/jars-info.txt");   
	 
			Node fileNode = folderNode.addNode(file.getName(), "nt:file");
			
			Node resourceNode = fileNode.addNode("jcr:content", "nt:resource");
			resourceNode.addMixin("mix:referenceable"); 
			resourceNode.setProperty("jcr:mimeType", "text/html");
			resourceNode.setProperty("jcr:encoding", "");
			resourceNode.setProperty("jcr:data", new BinaryImpl(new FileInputStream(file))); 
			
			Calendar lastModified = Calendar.getInstance();
			lastModified.setTimeInMillis(file.lastModified());
			resourceNode.setProperty("jcr:lastModified", lastModified); 
			
			Property property = resourceNode.getProperty("jcr:data");
			
			Binary binary = property.getBinary(); 
			
			
			InputStream inputStream = binary.getStream();
		 
			
			//파일의 바이트 길이구하기 
			int fileLenth = (int) file.length();

			//바이트 길이만큼의 바이트형 배열 생성
			byte[] buffer = new byte[500];

			//fileInputStream으로 배열의 내용을 읽어오기
			inputStream.read(buffer);

			//바이트코드 출력
			for (int index = 0; index < file.length(); index++) {
				System.out.print((char)buffer[index] );
			}
			

			session.save();   
		} catch (LoginException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RepositoryException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (session != null)
				session.logout();
		}
	}

}
